package com.glela.platform.service.impl;

import com.glela.platform.util.UserUtil;
import java.util.ArrayList;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.glela.api.im.rongcloud.ApiHttpClient;
import com.glela.api.im.rongcloud.vo.SdkHttpResult;
import com.glela.common.beans.FormatType;
import com.glela.common.constant.BaseConstants;
import com.glela.common.constant.BaseRestrictionsEnum;
import com.glela.common.util.Config;
import com.glela.common.util.DateUtil;
import com.glela.common.util.DateUtils;
import com.glela.common.util.HttpUtil;
import com.glela.common.util.StringUtil;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.mapper.ChangeProcessLogMapper;
import com.glela.platform.mapper.CheckCodeMapper;
import com.glela.platform.mapper.GivePromotionHistoryMapper;
import com.glela.platform.mapper.GivePromotionListMapper;
import com.glela.platform.mapper.PromotionDetailMapper;
import com.glela.platform.mapper.PromotionMapper;
import com.glela.platform.mapper.TalentJobMapper;
import com.glela.platform.mapper.UndefinedUserMapper;
import com.glela.platform.mapper.UserInfoMapper;
import com.glela.platform.mapper.UserMapper;
import com.glela.platform.mapper.UserPromotionMapper;
import com.glela.platform.model.BaseRestrictions;
import com.glela.platform.model.ChangeProcessLog;
import com.glela.platform.model.CheckCode;
import com.glela.platform.model.PromotionDetail;
import com.glela.platform.model.UndefinedUser;
import com.glela.platform.model.User;
import com.glela.platform.model.UserInfo;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.model.response.ResponseResultModel;
import com.glela.platform.service.BaseRestrictionsService;
import com.glela.platform.service.TokenService;
import com.glela.platform.service.UndefinedUserService;
import com.glela.platform.service.UserMoneyService;
import com.glela.platform.service.UserService;
import com.glela.platform.vo.WeChatTokenVo;
import com.glela.platform.vo.WeChatUserInfoVo;

@Service("undefinedUserService")
public class UndefinedUserServiceImpl implements UndefinedUserService {

	@Resource
	private UndefinedUserMapper UndefinedUserMapper;
	@Resource
	private UserMapper userMapper;
	@Resource
	private UserInfoMapper userInfoMapper;
	@Resource
	private CheckCodeMapper checkCodeMapper;
	@Autowired
	private TokenService tokenService;
	@Autowired
	private PromotionDetailMapper promotionDetailMapper;
	@Autowired
	private UserPromotionMapper userPromotionMapper;
	@Autowired
	private BaseRestrictionsService baseRestrictionsService;
	@Autowired
	private ChangeProcessLogMapper LogMapper;
	@Resource
	private PromotionMapper promotionMapper;
	@Autowired
	private UserMoneyService userMoneyService;
	@Autowired
	private TalentJobMapper talentJobMapper;
	@Autowired
	private GivePromotionHistoryMapper givePromotionHistoryMapper;
	@Autowired
	private GivePromotionListMapper givePromotionListMapper;
	@Autowired
	private UserService userService;
	
	
	private static Logger			logger			= LoggerFactory.getLogger(UndefinedUserServiceImpl.class);
	
	private void setUserToken(User user,String clientType) throws Exception {
		user.setToken(tokenService.SaveToken2(user,clientType));
		user.setPicture(user.getPicture());
		SdkHttpResult sdkHttpResult;
		BaseRestrictions baseRestrictions = baseRestrictionsService.getBaseRestrictionsForCache("RONG_CLOUD_CREATE_TOKEN");
		if (null != baseRestrictions) {
			if (baseRestrictions.getStatus().toString().equals("0")) {//禁用
				sdkHttpResult = new SdkHttpResult(200, "");//返回空字符串
			} else {
				sdkHttpResult = ApiHttpClient.getToken(String.valueOf(user.getId()), user.getUserName(),
						user.getPicture(), FormatType.json);
			}
		} else {
			sdkHttpResult = ApiHttpClient.getToken(String.valueOf(user.getId()), user.getUserName(),
					user.getPicture(), FormatType.json);
		}
		user.setRongCloudToken(sdkHttpResult.getResult());
		// 缓存用户信息
		//this.userService.getUserById(user.getId());
		//this.userService.cacheUser(user.getId());
		this.userService.getUserByPersionId(user.getRecommendFrom());
	}

	@Override
	public ResponseEntity<?> getUndefinedUserByUndefinedId(String undefinedId, String nickName, String urlHeader,String clientType) {
		// TODO Auto-generated method stub
		UndefinedUser undefinedUser = UndefinedUserMapper.selectUndefinedUserByUndefinedId(undefinedId,2);
		//没有第三方信息 添加返回
		if (undefinedUser == null) {
			UndefinedUserMapper.insertUndefinedUser(undefinedId, 2,0,nickName,urlHeader);
			UndefinedUser undefinedUser2 = UndefinedUserMapper.selectUndefinedUserByUndefinedId(undefinedId,2);
			return new ResponseEntity<>(new ResponseResultModel<UndefinedUser>(undefinedUser2), HttpStatus.OK);
		}
		//有第三方信息但没有绑定用户 直接返回
		if(undefinedUser.getUserId()==0){
			UndefinedUser undefinedUser3 = UndefinedUserMapper.selectUndefinedUserByUndefinedId(undefinedId,2);
			return new ResponseEntity<>(new ResponseResultModel<UndefinedUser>(undefinedUser3), HttpStatus.OK);
		}
		User user = new User();
		user = userMapper.selectUserEntityByIdNoPassword(undefinedUser.getUserId());
		if(user==null){
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20169), HttpStatus.OK);
		}
		BaseRestrictions baseRestrictions = baseRestrictionsService.getBaseRestrictionsForCache(BaseRestrictionsEnum.APP_LOGIN_FLAG);
		if (baseRestrictions==null || baseRestrictions.getExperience()==1) {
		// 非店主不能登录小铺来了APP
			if ("APP".equals(clientType.toUpperCase())) {
				if (user.getRoleId() < 3) {
					logger.info("小白用户 "+user.getId()+" 角色ID "+user.getRoleId()+" 于 "+DateUtils.getFullDate()+" 登录，被拒绝");
					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20276), HttpStatus.OK);
				}
			}
		}
		UserInfo userInfo = userInfoMapper.selectByUserId(undefinedUser.getUserId());
		if(userInfo==null){
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20170), HttpStatus.OK);
		}
		user.setUserInfo(userInfo);
		user.setOpenId(undefinedId);
		try {
			//登录token生成、放入
			
			setUserToken(user,clientType);
		} catch (Exception e) {
		}
		return new ResponseEntity<>(new ResponseResultModel<User>(user), HttpStatus.OK);
	}


	@Override
	public ResponseEntity<?> getUndefinedUserAdd(String mobile, String undefinedId, 
			String validCode,String password,int undefinedType, String storeUserName,
			int regSource, String deviceCode,String clientType,long talentID) {
		// TODO Auto-generated method stub
		// User user=new User();
		//第三方登录类型未传则为1 APP微信登录
		if(undefinedType==0){
			undefinedType=1;
		}
		CheckCode checkCode = checkCodeMapper.selectCheckCodeByMobile(mobile);
		if (checkCode == null || !checkCode.getCode().equals(validCode)) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20109), HttpStatus.OK);
		}
		if (deviceCode == null) {
			deviceCode = "";
		}
		String nowDate = DateUtil.getNow();
		User user3 = userMapper.selectUserByUserNameNopassword(mobile);
		//没有注册过
		if (user3 == null) {
			BaseRestrictions baseRestrictions = baseRestrictionsService.getBaseRestrictionsForCache(BaseRestrictionsEnum.APP_LOGIN_FLAG);
			if (baseRestrictions==null || baseRestrictions.getExperience()==1) {
			// 非店主不能登录小铺来了APP
				if ("APP".equals(clientType.toUpperCase())) {
					logger.info("小白用户 "+mobile+" 角色ID  于 "+DateUtils.getFullDate()+" 登录，被拒绝");
					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20276), HttpStatus.OK);
				}
			}
			// 修改第三方绑定信息
			//微信平台进入
			UndefinedUser undefinedUser = UndefinedUserMapper.selectUndefinedUserByUndefinedId(undefinedId,undefinedType);
			if(undefinedUser==null){
				//绑定手机号码时不能出现没有第三方登录信息的情况
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20170), HttpStatus.OK);
			}
			//已授权 但没有绑定用户
			//绑定成功后返回
			/*int sign = userInfoMapper.selectUserinfoMaxSign();
			if (sign <= 0) {
				sign = 100000;
			}
			sign += 1;
			String persionId = RandomUtil.getRandomStr(2) + sign;*/
			
			//新用户注册 记录日志
			ChangeProcessLog Log=new ChangeProcessLog();
			Log.setDescription("新用户注册(第三方注册)");
			
			String recommendFrom = "";
			Long storeUserId = 0L;// 校妆姐姐店铺的店主ID
			int bindRecommendMode = 0;// 小白会员绑定讲师的方式： 0 小白扫码绑定的  1 系统后台给小白会员指定的讲师
			// 如果店主电话不能空 校验店主是否存在
			if (!StringUtil.isEmpty(storeUserName)) {
				storeUserId = userMapper.selectIdByUserName(storeUserName);
				if (storeUserId != null && storeUserId != 0) {
					User storeUser = userMapper.selectByPrimaryKey(storeUserId);
					if (!StringUtil.isEmpty(storeUser.getRecommendFrom())&&storeUser.getRoleId()>=3) {
						recommendFrom = storeUser.getRecommendFrom();
						Log.setDescription("2017年暑期开学季《送水活动》扫码注册");
					} else {
						return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C40012), HttpStatus.OK);
					}
				} else {
					return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C40012), HttpStatus.OK);
				}
			} else if(talentID>0){
				User user= userMapper.selectUserBaseInfoById(talentID);
				  if(user==null){
					  return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C40012), HttpStatus.OK);
				  }
				storeUserId = user.getId();
				if (!StringUtil.isEmpty(user.getRecommendFrom())&&user.getRoleId()>=3) {
					recommendFrom = user.getRecommendFrom();
					Log.setDescription("2017年暑期开学季《送水活动》扫码注册");
				} else {
					return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C40012), HttpStatus.OK);
				}		
			} else {// 店主电话为空值  默认取校妆姐姐的身份标识
				// 默认普通推荐人身份为校妆姐姐
				// 校妆姐姐店铺的店主ID
				storeUserId = BaseConstants.XZ_SISTER;
				if (storeUserId != null) {
					UserInfo xzjjUserInfo = userInfoMapper.selectByUserId(Long.valueOf(storeUserId));
					if (xzjjUserInfo != null) {
						recommendFrom = xzjjUserInfo.getPersionId();
						bindRecommendMode = 1;
					}
				}
			}
			if("".equals(recommendFrom)){
				userMapper.insertUserNew(mobile, password, "", undefinedUser.getNickName(),undefinedUser.getPicture(),bindRecommendMode,deviceCode,nowDate);
			} else {
				userMapper.insertUserNew(mobile, password, recommendFrom, undefinedUser.getNickName(),undefinedUser.getPicture(),bindRecommendMode,deviceCode,nowDate);
			}
			
			Log.setMethod("UndefinedUserServiceImpl.getUndefinedUserAdd");
			Log.setPrimaryID("");
			Log.setTableName("yg_user.c_user");
			Log.getAfterMap().put("recommendFrom",recommendFrom);
			LogMapper.insert(Log);
			
			User user = userMapper.selectUserByUserName(mobile);
			
			// 检查是否存在usermoney信息
			userMoneyService.checkExistUserMoney(user.getId());
			
			userInfoMapper.insertUserInfoNew(user.getId(), UserUtil.getPersonId(user.getId()), user.getId().intValue(), 0, regSource);
			UserInfo userInfo = userInfoMapper.selectByUserId(user.getId());
			UndefinedUserMapper.updateUndefinedByIdAndUserUd(user.getId(), undefinedId, undefinedType);
			//优惠券信息
			user.setPromotionDetailList(new ArrayList<PromotionDetail>());
			
			//是否第一次绑定
			user.setFirstBindPhone(true);
			try {
				setUserToken(user,clientType);
			} catch (Exception e) {
				
			}
			user.setUserInfo(userInfo);
			return new ResponseEntity<>(new ResponseResultModel<User>(user), HttpStatus.OK);
		}else {// 修改店铺绑定关系
			BaseRestrictions baseRestrictions = baseRestrictionsService.getBaseRestrictionsForCache(BaseRestrictionsEnum.APP_LOGIN_FLAG);
			if (baseRestrictions==null || baseRestrictions.getExperience()==1) {
				// 非店主不能登录小铺来了APP  1限制登录，0不限制
				if ("APP".equals(clientType.toUpperCase())) {
					if(user3.getRoleId() < 3){
						logger.info("小白用户 "+user3.getId()+" 角色ID "+user3.getRoleId()+" 于 "+DateUtils.getFullDate()+" 登录，被拒绝");
						return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20276), HttpStatus.OK);
					}
				}
			}
			if (!StringUtil.isEmpty(storeUserName)) {
				Long storeUserId = userMapper.selectIdByUserName(storeUserName);
				if (storeUserId != null && storeUserId != 0) {
					User storeUser = userMapper.selectByPrimaryKey(storeUserId);
					if (!StringUtil.isEmpty(storeUser.getRecommendFrom())&&storeUser.getRoleId()>=3) {
						if(user3.getRoleId()<3){
							String recommendFrom = storeUser.getRecommendFrom();
							userMapper.updateRecommendFromByIdNew(recommendFrom,0,deviceCode,nowDate,user3.getId());
						}
					} else {
						return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C40012), HttpStatus.OK);
					}
				} else {
					return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C40012), HttpStatus.OK);
				}
			}else if(talentID>0){
				User user= userMapper.selectUserBaseInfoById(talentID);
				  if(user==null){
					  return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C40012), HttpStatus.OK);
				  }
				  if (!StringUtil.isEmpty(user.getRecommendFrom())&&user.getRoleId()>=3) {
						if(user3.getRoleId()<3){
							String recommendFrom = user.getRecommendFrom();
							userMapper.updateRecommendFromByIdNew(recommendFrom,0,deviceCode,nowDate,user3.getId());
						}
					} else {
						return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C40012), HttpStatus.OK);
					}
			}
		}
		//在APP中有用户
		UndefinedUser ygundefinedUser = UndefinedUserMapper.selectUndefinedUserByUndefinedId(undefinedId,undefinedType);
		if(ygundefinedUser==null){
			//绑定手机号码时不能出现没有第三方登录信息的情况
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20170), HttpStatus.OK);
		}
		UndefinedUserMapper.updateUndefinedByIdAndUserUd(user3.getId(), undefinedId, undefinedType);
		UserInfo userInfo=userInfoMapper.selectByUserId(user3.getId());
		if(userInfo==null){
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20169), HttpStatus.OK);
		}
		try {
			setUserToken(user3,clientType);
		} catch (Exception e) {
		}
		//是否第一次绑定
		user3.setFirstBindPhone(false);
		user3.setUserInfo(userInfo);
		return new ResponseEntity<>(new ResponseResultModel<User>(user3), HttpStatus.OK);
	}

 
	@Override
	public ResponseEntity<?> appUndefinedUserAdd(String code,String clientType) {
		// TODO Auto-generated method stub
		try {
			//			ResponseUnDefinedUserVo responseUnDefinedUserVo=new ResponseUnDefinedUserVo();
			//获取token 第一步
			StringBuffer URL = new StringBuffer();
			URL.append("https://api.weixin.qq.com/sns/oauth2/access_token?appid=").append(Config.getString("wechat.appId0")).append("&secret=").append(Config.getString("wechat.secret0")).append("&code=").append(code).append("&grant_type=authorization_code");
			String json = HttpUtil.doGet(URL.toString());
			WeChatTokenVo vo = JSONObject.parseObject(json, WeChatTokenVo.class);
			if (vo.getErrmsg() != null) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20146), HttpStatus.OK);
			}
			//第二步 拉取用户信息
			StringBuffer URL1 = new StringBuffer();
			URL1.append("https://api.weixin.qq.com/sns/userinfo?access_token=").append(vo.getAccess_token()).append("&openid=").append(vo.getOpenid()).append("&lang=zh_CN");
			String json1 = HttpUtil.doGet(URL1.toString());
			WeChatUserInfoVo vo1 = JSONObject.parseObject(json1, WeChatUserInfoVo.class);
			//如果拉取失败就刷新
			if (vo1.getErrmsg() != null) {
				//					responseUnDefinedUserVo.setMsg("拉取用户信息失败 准备进行刷新。。。"+vo1.getErrmsg());
				//					StringBuffer URL2 = new StringBuffer() ;
				//					URL2.append("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=")
				//						.append("wx645f16ce6b3c8894").append("&grant_type=REFRESH_TOKEN")
				//						.append("&refresh_token=").append(vo.getRefresh_token());
				//					String json2 = HttpUtil.doGet(URL2.toString()) ;
				//					WeChatTokenVo vo2 = JSONObject.parseObject(json2, WeChatTokenVo.class);
				//					if (vo2.getAccess_token()==null) {
				//						//刷新再失败就没办法了 一边玩儿去
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20153), HttpStatus.OK);
				//					}
			}
			User user = new User();
			String unUndefinedId = vo.getOpenid();
			//String unUndefinedId="o7lhVs9vc3crg9oU2jUSSsvGdD9U1111111";
			UndefinedUser undefinedUser = UndefinedUserMapper.selectUndefinedUserByUndefinedId(unUndefinedId, 1);
			if (undefinedUser == null) {
				UndefinedUserMapper.insertUndefinedUser(unUndefinedId, 1, 0, vo1.getNickname(), vo1.getHeadimgurl());
				//UndefinedUserMapper.insertUndefinedUser(unUndefinedId, 1, 0,"夏天","/qq/qq");
				//setUserToken(user,TokenTypeEnum.T1.getCode());
				UndefinedUser undefinedUser1 = UndefinedUserMapper.selectUndefinedUserByUndefinedId(unUndefinedId, 1);
				user.setNickName(undefinedUser1.getNickName());
				user.setPicture(undefinedUser1.getPicture());
				user.setOpenId(unUndefinedId);
				user.setId(0L);
				return new ResponseEntity<>(new ResponseResultModel<User>(user), HttpStatus.OK);
			}
			if (undefinedUser.getUserId() == 0) {
				user.setNickName(undefinedUser.getNickName());
				user.setPicture(undefinedUser.getPicture());
				user.setOpenId(unUndefinedId);
				user.setId(0L);
				return new ResponseEntity<>(new ResponseResultModel<User>(user), HttpStatus.OK);
			}
			//有第三方登录信息
			user = userMapper.selectUserEntityByIdNoPassword(undefinedUser.getUserId());
			if (user == null) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20169), HttpStatus.OK);
			}
			BaseRestrictions baseRestrictions = baseRestrictionsService.getBaseRestrictionsForCache(BaseRestrictionsEnum.APP_LOGIN_FLAG);
			if (baseRestrictions==null || baseRestrictions.getExperience()==1) {
				// 非店主不能登录小铺来了APP
				if ("APP".equals(clientType.toUpperCase())) {
					if (user.getRoleId() < 3) {
						logger.info("小白用户 "+user.getId()+" 角色ID "+user.getRoleId()+" 于 "+DateUtils.getFullDate()+" 登录，被拒绝");
						return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20276), HttpStatus.OK);
					}
				}
			}
			UserInfo userInfo = userInfoMapper.selectByUserId(undefinedUser.getUserId());
			if (userInfo == null) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20170), HttpStatus.OK);
			}
			user.setUserType(1);
			user.setUserInfo(userInfo);
			user.setOpenId(unUndefinedId);
			user.setPersionId(userInfo.getPersionId());
			setUserToken(user,clientType);
			return new ResponseEntity<>(new ResponseResultModel<User>(user), HttpStatus.OK);
		} catch (Exception e) {
			// TODO: handle exception
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	
}
